import { api } from '@/utils/request'
import type { 
  LoginForm, 
  LoginResponse, 
  User, 
  Permission,
  ApiResponse 
} from '@/types'

// 缓存键
const CACHE_KEYS = {
  USER_PERMISSIONS: 'user_permissions_cache'
}

// 缓存工具函数
function setCache<T>(key: string, data: T, expiry: number = 30 * 60 * 1000): void {
  const cacheItem = {
    data,
    timestamp: Date.now(),
    expiry
  }
  localStorage.setItem(key, JSON.stringify(cacheItem))
}

function getCache<T>(key: string): T | null {
  try {
    const cached = localStorage.getItem(key)
    if (!cached) return null

    const cacheItem = JSON.parse(cached)
    const now = Date.now()
    
    // 检查是否过期
    if (now - cacheItem.timestamp > cacheItem.expiry) {
      localStorage.removeItem(key)
      return null
    }
    
    return cacheItem.data
  } catch (error) {
    console.warn(`缓存解析失败 [${key}]:`, error)
    localStorage.removeItem(key)
    return null
  }
}

export class AuthService {
  /**
   * 手机号登录
   */
  static async adminLogin(loginData: LoginForm): Promise<LoginResponse> {
    const response = await api.post<LoginResponse>('/auth/api-admin/authUser/doLogin', {
      phone: loginData.phone
    })
    return response.data
  }

  /**
   * 获取当前用户权限列表（带缓存）
   */
  static async getCurrentUserPermissions(): Promise<Permission[]> {
    // 先检查缓存
    const cachedPermissions = getCache<Permission[]>(CACHE_KEYS.USER_PERMISSIONS)
    
    if (cachedPermissions) {
      return cachedPermissions
    }

    // 从服务器获取权限数据
    const response = await api.get<Permission[]>('/auth/api-admin/authPermission/getPermissionListByCurrentUser')
    
    // 缓存权限数据（30分钟）
    setCache(CACHE_KEYS.USER_PERMISSIONS, response.data, 30 * 60 * 1000)
    
    return response.data
  }

  /**
   * 获取用户详情
   */
  static async getUserDetail(id: number): Promise<User> {
    const response = await api.get<User>(`/auth/api-miniApp/authUser/get/${id}`)
    return response.data
  }

  /**
   * 更新用户信息
   */
  static async updateUser(userData: Partial<User>): Promise<boolean> {
    const response = await api.post<boolean>('/auth/api-miniApp/authUser/update', userData)
    return response.data
  }
}

// 默认导出单例实例
export const authService = AuthService 